package net.quanter.shield.mq;

import lombok.Data;
import lombok.ToString;
import net.quanter.shield.mq.rocketmq.utils.ObjectUtils;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static net.quanter.shield.mq.MQProducer.MSG_ID_KEY;

/**
 * 消息统一传输对象
 *
 * @param <T> 具体消息实体
 * @author yaoyuanjun
 */
@Data
@ToString
public class MQMessageVO<T> implements Serializable {
    private static final long serialVersionUID = -223423340408383597L;
    private String topic;
    private String tag;
    private String shardKey;
    private T obj;
    private final Map<String, String> properties = new ConcurrentHashMap<>();

    /**
     * 以下是从rocketmq的consumer端获取的，发送端无须关心
     */
    private Long offset;
    private Long queueOffset;
    private String messageId;
    private String requestId;
    private String messageMD5;
    private Long publishTime;
    private Long firstConsumeTime;
    private Long nextConsumeTime;
    private Integer consumedTimes;

    public void put(String key, String value) {
        properties.put(key, value);
    }

    public void putAll(Map<String,String> map) {
        properties.putAll(map);
    }

    public byte[] getBase64Obj() {
        return ObjectUtils.objectToByteArray(obj);
    }

    public String getMsgId() {
        if (properties.containsKey(MSG_ID_KEY)) {
            return properties.get(MSG_ID_KEY);
        } else {
            return messageId;
        }
    }
}
